import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus'
import router from '../router'

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
    timeout: 50000
});
let loadingAlert = null;
service.interceptors.request.use(
    config => {
        loadingAlert = ElLoading.service({
            lock: true,
            text: '加载中...',
            customClass: 'custom-loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
        })
        // 设置公用请求头
        config.headers.businessType = "4"
        config.headers.websiteName = window.location.hostname
        // config.headers.platformNo = "KB2104300057"
        let token = localStorage.getItem("linggong_token")
        if(token) {
            config.headers.Authorization = token
            let info = JSON.parse(localStorage.getItem("linggong_info"))
            if(!config.headers.businessId) {
                // config.headers.businessId = info.businessId
            }
            // config.headers.businessNo = info.businessNo
            config.headers.platformId = info.platformId
            config.headers.platformNo = info.platformNo
            config.headers["Content-type"] = "application/json";
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        loadingAlert.close()
        if (response.status === 200) {
			if(response.data.code === 0) {
				return response.data
			}else if(response.data.code === 4) {
                // token过期跳转至登录
                ElMessage({
					showClose: true,
					dangerouslyUseHTMLString: true,
					message: "请重新登录",
					type: 'warning'
				})
                router.push({name: 'Login'})
			}else {
                if(response.data.msg != undefined) {
                    ElMessage({
                        showClose: true,
                        dangerouslyUseHTMLString: true,
                        message: response.data.msg,
                        type: 'error'
                    })
                }
				return response.data
			}
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        loadingAlert.close()
        return Promise.reject();
    }
);


export default service;
